// 权限判断
const models = require('../db/mysqldb/index')
const sequelize = require('sequelize/index')
const Op = sequelize.Op
const {
  ErrorModel,noAuthErrorModel
} = require('../utils/index')
const auth = async (req, res, next) => {
  const { user, url,method} = req
  const {role_id} = user
  try {
    const menu_id_arr =await models.sys_role_menu.findAll({
      where:{
        role_id
      }
    })
    const idArr = []
    menu_id_arr.map(item=>{
      idArr.push(item.menu_id)
    })
    const premissionUrl = await models.sys_menu.findOne({
      where:{
        method,
        url,
        menu_id: {
          [Op.in]: idArr
        }
      }
    })
    if(premissionUrl){
      next()
      return
    }else{
      res.json(new noAuthErrorModel([],'当前功能用户无权限或者当前用户已被网站管理员禁用此功能，请联系管理员开启!'));
      return
    }
  } catch (error) {
    res.json(new ErrorModel([],error.message))
    return
  }
}
module.exports = {
  auth
}